package com.tencent.txcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.tencent.txcc.domain.PayOrder;
import com.tencent.txcc.dto.PayDto;
import com.tencent.txcc.enums.GlobleExceptionCode;
import com.tencent.txcc.service.IPayOrderService;
import com.tencent.txcc.util.AssertUtil;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@RocketMQMessageListener(
        consumerGroup = "order-consumer-group",
        topic = "order-topic",
        selectorExpression = "order-tag"
)
public class CourseOrderPayTxConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;


    @Override
    public void onMessage(MessageExt messageExt) {
        // 强转为byte[]
        byte[] body = messageExt.getBody();
        // 将bytes转为字符串再转为JSON对象
        String str = new String(body, StandardCharsets.UTF_8);
        PayDto payDto = JSON.parseObject(str, PayDto.class);
        // 判断对象是否为空，如果为空则说明对象没有消息传过来，直接回滚
        AssertUtil.isNotNull(payDto, GlobleExceptionCode.PARAM_IS_NULL);
        PayOrder payOrder = payOrderService.selectByOrderNo(payDto.getOrderNo());
        if (payOrder != null){
            return;
        }

        // 保存支付单
        payOrder = new PayOrder();
        payOrder.setAmount(payDto.getTotalAmount());
        payOrder.setCreateTime(new Date());
        payOrder.setExtParams(payDto.getExtParams());
        payOrder.setOrderNo(payDto.getOrderNo());
        payOrder.setPayStatus(PayOrder.WAIT_PAY_STATUS);
        payOrder.setPayType(payDto.getPayType());
        payOrder.setUserId(payDto.getUserId());
        payOrder.setSubject(payDto.getTitle());
        payOrder.setExtParams(payDto.getExtParams());
        payOrderService.insert(payOrder);
    }
}
